import { App, PluginSettingTab, Setting, Notice } from 'obsidian';
import DocumentSharePlugin from './main';
import { ApiClient } from './api-client';

export class DocumentShareSettingTab extends PluginSettingTab {
  plugin: DocumentSharePlugin;

  constructor(app: App, plugin: DocumentSharePlugin) {
    super(app, plugin);
    this.plugin = plugin;
  }

  display(): void {
    const { containerEl } = this;

    containerEl.empty();
    containerEl.createEl('h2', { text: '文档分享设置' });

    // API 地址
    new Setting(containerEl)
      .setName('API 地址')
      .setDesc('服务端 API 地址（例如：https://your-domain.com/api）')
      .addText(text =>
        text
          .setPlaceholder('https://your-domain.com/api')
          .setValue(this.plugin.settings.apiUrl)
          .onChange(async (value) => {
            this.plugin.settings.apiUrl = value.trim().replace(/\/$/, '');
            await this.plugin.saveSettings();
          }),
      );

    // ---------------- 登录方式：Tab 切换 ----------------
    containerEl.createEl('h3', { text: 'API Token 配置' });
    containerEl.createEl('p', {
      text: '可以直接填写 Token，或通过账号密码登录获取 Token。',
      cls: 'setting-item-description',
    });

    // Tab 头部
    const tabsHeader = containerEl.createDiv({ cls: 'document-share-auth-tabs' });
    const tokenTabBtn = tabsHeader.createEl('button', { text: 'Token 配置' });
    const accountTabBtn = tabsHeader.createEl('button', { text: '账号密码登录' });
    tokenTabBtn.addClass('document-share-auth-tab-button');
    accountTabBtn.addClass('document-share-auth-tab-button');

    // Tab 内容容器
    const tokenTabContent = containerEl.createDiv({ cls: 'document-share-auth-tab-content' });
    const accountTabContent = containerEl.createDiv({ cls: 'document-share-auth-tab-content' });

    const setActiveTab = (tab: 'token' | 'account') => {
      if (tab === 'token') {
        tokenTabBtn.addClass('is-active');
        accountTabBtn.removeClass('is-active');
        (tokenTabContent as HTMLElement).style.display = '';
        (accountTabContent as HTMLElement).style.display = 'none';
      } else {
        accountTabBtn.addClass('is-active');
        tokenTabBtn.removeClass('is-active');
        (accountTabContent as HTMLElement).style.display = '';
        (tokenTabContent as HTMLElement).style.display = 'none';
      }
    };

    tokenTabBtn.addEventListener('click', () => setActiveTab('token'));
    accountTabBtn.addEventListener('click', () => setActiveTab('account'));

    // 默认显示 Token 配置
    setActiveTab('token');

    // ------ Token 配置 Tab ------
    new Setting(tokenTabContent)
      .setName('API Token')
      .setDesc('使用服务器命令生成的 Token')
      .addText(text =>
        text
          .setPlaceholder('输入您的 API Token')
          .setValue(this.plugin.settings.apiToken)
          .onChange(async (value) => {
            this.plugin.settings.apiToken = value.trim();
            await this.plugin.saveSettings();
          }),
      );

    new Setting(tokenTabContent)
      .setName('更换 Token')
      .setDesc('使用当前 Token 换取新 Token（旧 Token 将立即失效）')
      .addButton(button =>
        button
          .setButtonText('更换 Token')
          .setCta()
          .onClick(async () => {
            await this.rotateToken();
          }),
      );

    new Setting(tokenTabContent)
      .setName('测试连接')
      .setDesc('测试服务器连接和 API Token 是否有效')
      .addButton(button =>
        button
          .setButtonText('测试连接')
          .onClick(async () => {
            await this.testConnection();
          }),
      );

    // ------ 账号密码登录 Tab ------
    let nameValue = '';
    new Setting(accountTabContent)
      .setName('账号')
      .setDesc('用于注册或登录的账号')
      .addText(text =>
        text
          .setPlaceholder('输入账号')
          .onChange((value) => {
            nameValue = value.trim();
          }),
      );

    let passwordValue = '';
    new Setting(accountTabContent)
      .setName('密码')
      .setDesc('账户密码（至少 6 个字符）')
      .addText(text => {
        text
          .setPlaceholder('输入密码')
          .onChange((value) => {
            passwordValue = value.trim();
          });
        text.inputEl.type = 'password';
      });

    new Setting(accountTabContent)
      .setName('操作')
      .setDesc('选择注册新账号或使用已有账号登录')
      .addButton(button =>
        button
          .setButtonText('注册')
          .onClick(async () => {
            await this.registerUser(nameValue, passwordValue);
          }),
      )
      .addButton(button =>
        button
          .setButtonText('登录获取 Token')
          .setCta()
          .onClick(async () => {
            await this.loginAndGetToken(nameValue, passwordValue);
          }),
      );

    // ---------------- 默认设置 ----------------
    containerEl.createEl('h3', { text: '默认设置' });

    new Setting(containerEl)
      .setName('默认主题')
      .setDesc('上传文档时的默认主题')
      .addDropdown(dropdown =>
        dropdown
          .addOption('github', 'GitHub')
          .addOption('dark', 'Dark')
          .addOption('minimal', 'Minimal')
          .addOption('notion', 'Notion')
          .addOption('obsidian', 'Obsidian')
          .setValue(this.plugin.settings.defaultTheme)
          .onChange(async (value) => {
            this.plugin.settings.defaultTheme = value as any;
            await this.plugin.saveSettings();
          }),
      );

    new Setting(containerEl)
      .setName('默认可见性')
      .setDesc('上传文档时的默认可见性')
      .addDropdown(dropdown =>
        dropdown
          .addOption('public', '公开')
          .addOption('private', '私密')
          .setValue(this.plugin.settings.defaultVisibility)
          .onChange(async (value) => {
            this.plugin.settings.defaultVisibility = value as any;
            await this.plugin.saveSettings();
          }),
      );

    new Setting(containerEl)
      .setName('默认密码')
      .setDesc('私密文档的默认密码（可选）')
      .addText(text =>
        text
          .setPlaceholder('留空则每次手动输入')
          .setValue(this.plugin.settings.defaultPassword)
          .onChange(async (value) => {
            this.plugin.settings.defaultPassword = value;
            await this.plugin.saveSettings();
          }),
      );

    // ---------------- 文档自动更新 ----------------
    containerEl.createEl('h3', { text: '文档自动更新' });

    new Setting(containerEl)
      .setName('启用文档自动更新')
      .setDesc('监听文件变化并自动更新到服务器（仅对已上传的文档生效）')
      .addToggle(toggle =>
        toggle
          .setValue(this.plugin.settings.enableAutoUpdate)
          .onChange(async (value) => {
            this.plugin.settings.enableAutoUpdate = value;
            await this.plugin.saveSettings();
            if (value) {
              new Notice('文档自动更新已启用');
            } else {
              new Notice('文档自动更新已禁用');
            }
          }),
      );

    new Setting(containerEl)
      .setName('文档更新延迟（毫秒）')
      .setDesc('文件修改后多久开始上传（避免频繁上传，建议 2000–5000）')
      .addText(text =>
        text
          .setPlaceholder('3000')
          .setValue(String(this.plugin.settings.autoUpdateDelay))
          .onChange(async (value) => {
            const delay = parseInt(value, 10);
            if (!isNaN(delay) && delay >= 1000) {
              this.plugin.settings.autoUpdateDelay = delay;
              await this.plugin.saveSettings();
            }
          }),
      );

    // ---------------- 其它 ----------------
    const footer = containerEl.createDiv({ cls: 'document-share-footer' });
    footer.style.marginTop = '2em';
    footer.style.paddingTop = '1em';
    footer.style.borderTop = '1px solid var(--background-modifier-border)';
    footer.style.textAlign = 'center';
    footer.style.color = 'var(--text-muted)';
    footer.style.fontSize = '0.9em';

    const link = footer.createEl('a', {
      text: '开源地址: https://gitee.com/miya0716/ob-share',
      href: 'https://gitee.com/miya0716/ob-share',
    });
    link.style.color = 'var(--text-accent)';
    link.style.textDecoration = 'none';
    link.addEventListener('mouseenter', () => {
      link.style.textDecoration = 'underline';
    });
    link.addEventListener('mouseleave', () => {
      link.style.textDecoration = 'none';
    });
  }

  async testConnection(): Promise<void> {
    const client = new ApiClient(this.plugin.settings);

    if (!this.plugin.settings.apiUrl || !this.plugin.settings.apiToken) {
      new Notice('请先配置 API 地址和 API Token');
      return;
    }

    new Notice('正在测试连接...');

    const success = await client.testConnection();

    if (success) {
      new Notice('连接成功！');
    } else {
      new Notice('连接失败，请检查配置。');
    }
  }

  async rotateToken(): Promise<void> {
    if (!this.plugin.settings.apiUrl || !this.plugin.settings.apiToken) {
      new Notice('请先配置 API 地址和当前的 API Token');
      return;
    }

    const confirmed = confirm(
      '确定要更换 Token 吗？\n\n' +
      '旧 Token 将立即失效，新 Token 会自动保存到配置中。',
    );

    if (!confirmed) {
      return;
    }

    new Notice('正在更换 Token...');

    const client = new ApiClient(this.plugin.settings);
    const response = await client.rotateToken();

    if (response.success && response.data?.token) {
      this.plugin.settings.apiToken = response.data.token;
      await this.plugin.saveSettings();

      new Notice('Token 已成功更换。');
      this.display();
    } else {
      new Notice(`更换失败: ${response.message || response.error}`);
    }
  }

  async registerUser(name: string, password: string): Promise<void> {
    if (!this.plugin.settings.apiUrl) {
      new Notice('请先配置 API 地址');
      return;
    }

    if (!name || !password) {
      new Notice('请输入账号和密码');
      return;
    }

    if (password.length < 6) {
      new Notice('密码至少需要 6 个字符');
      return;
    }

    new Notice('正在注册账号...');

    try {
      const url = `${this.plugin.settings.apiUrl}/register`;
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: name,
          password: password,
        }),
      });

      const data = await response.json();

      if (data.success) {
        new Notice(
          `注册成功！\n` +
          `账号: ${data.data.user.name}\n` +
          `现在可以使用“登录获取 Token”按钮获取 API Token。`,
          6000,
        );
      } else {
        const errorMsg = data.message || '注册失败';
        const errors = data.errors ? Object.values(data.errors).flat().join(', ') : '';
        new Notice(`${errorMsg}${errors ? ': ' + errors : ''}`);
      }
    } catch (error: any) {
      new Notice(`请求失败: ${error.message}`);
      console.error('Register error:', error);
    }
  }

  async loginAndGetToken(name: string, password: string): Promise<void> {
    if (!this.plugin.settings.apiUrl) {
      new Notice('请先配置 API 地址');
      return;
    }

    if (!name || !password) {
      new Notice('请输入账号和密码');
      return;
    }

    new Notice('正在登录并获取 Token...');

    try {
      const url = `${this.plugin.settings.apiUrl}/login`;
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: name,
          password: password,
        }),
      });

      const data = await response.json();

      if (data.success && data.data?.token) {
        this.plugin.settings.apiToken = data.data.token;
        await this.plugin.saveSettings();

        new Notice(
          `登录成功！\n` +
          `账号: ${data.data.user.name}\n` +
          `Token 已自动保存到配置中。`,
          6000,
        );

        this.display();
      } else {
        const errorMsg = data.message || '登录失败';
        new Notice(errorMsg);
      }
    } catch (error: any) {
      new Notice(`请求失败: ${error.message}`);
      console.error('Login error:', error);
    }
  }
}

